package com.raysdata.smartcity.web.sys;

import com.alibaba.fastjson.JSON;
import com.raysdata.smartcity.HelperClazz;
import com.raysdata.smartcity.Key;
import com.raysdata.smartcity.Md5;
import com.raysdata.smartcity.dto.Role;
import com.raysdata.smartcity.dto.User;
import com.raysdata.smartcity.flow.activiti.dao.IdentityDao;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by liux on 2016/10/14.
 * 用户信息controller
 */
@Controller
@RequestMapping(value = "/user")
public class UserController extends com.raysdata.smartcity.web.BaseController {

    /**
     * 用户管理页跳转
     * @param model
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/toUserIndex", method = RequestMethod.GET)
    public String toUserIndex(Model model, HttpServletRequest request, HttpServletResponse response) {
        request.setAttribute("pmList",commonDao.getAttrListByKey(Key.RANGE_TYPE));
        return "smartcity/userManage/userList";
    }

    /**
     * 获取用户列表数据
     * @param request
     * @param response
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    @RequestMapping(value = "/getUserList")
    public void getUserList(HttpServletRequest request,HttpServletResponse response) throws InvocationTargetException, IllegalAccessException {
        Map filter= WebUtils.getParametersStartingWith(request, "query_");
        User user=new User();
        BeanUtils.populate(user, filter);
        List<User> users = new ArrayList<User>();
        int page = HelperClazz.getCurrentPage(request);
        int count = HelperClazz.getPageSize(request);
        users = userDao.queryUsers(page,count,user);
        HelperClazz.renderJson(response,HelperClazz.toJSON4Page(users));
    }

    /**
     * 新增用户页跳转
     * @param modele
     * @param request
     * @return
     */
    @RequestMapping(value = "/toUserAdd")
    public String toUserAdd(Model modele,HttpServletRequest request){
        request.setAttribute("pmList",commonDao.getAttrListByKey(Key.RANGE_TYPE));
        return "smartcity/userManage/userAdd";
    }

    /**
     * 修改用户页跳转
     * @param modele
     * @param request
     * @return
     */
    @RequestMapping(value = "/toUserUpdate")
    public String toUserUpdate(Model modele,HttpServletRequest request){
        String id=request.getParameter("user_id");
        User user=this.userDao.getUserById(id);
        request.setAttribute("user",user);
        request.setAttribute("pmList",commonDao.getAttrListByKey(Key.RANGE_TYPE));
        return "smartcity/userManage/userUpdate";
    }

    /**
     * 保存
     * @param user
     * @param request
     * @param response
     */
    @RequestMapping(value = "/doSave")
    public void addSave(@ModelAttribute("user")User user, HttpServletRequest request, HttpServletResponse response){
        int result=-1;
        String type="";
        String content="";
        User u=(User)request.getSession().getAttribute("LoginUser");
        if(HelperClazz.isEmpty(user.getUser_id())) {
            user.setPassword(Md5.MD5(ADMIN_INIT_PWD));
            user.setCperson(u.getUser_id());
            user.setPermission(Key.PM_DEPT);
            result=userDao.addUser(user);
            result= identityDao.saveUser(user.getLogin_name());
            type=Key.LOG_ADD;
            content="新增用户："+user.getUser_name();
        }else{
            result=userDao.updUser(user);
            type=Key.LOG_UPDATE;
            content="修改用户："+user.getUser_name();
        }
        if(result==0){
            logDao.saveLog(request,content,type,u,user.getLogin_name(),Key.LOG_SUCCESS);
            HelperClazz.renderJson(response, "{\"success\":true,\"msg\":\"用户保存成功！\"}");
        }else{
            logDao.saveLog(request,content,type,u,user.getLogin_name(),Key.LOG_ERROR);
            HelperClazz.renderJson(response, "{\"success\":true,\"msg\":\"用户保存失败！\"}");
        }

    }

    /**
     * 根据ID删除用户
     * @param request
     * @param response
     */
    @RequestMapping(value = "/deleteUser")
    public void deleteUser(HttpServletRequest request,HttpServletResponse response){
        int result=-1;
        String id=request.getParameter("user_id");
        User user=userDao.getUserById(id);
        result=this.userDao.delUserById(user);
        result=identityDao.deleteUser(user.getLogin_name());
        String type=Key.LOG_DELETE;
        String content="删除用户："+user.getUser_name();
        if(result==0){
            logDao.saveLog(request,content,type,(User)request.getSession().getAttribute("LoginUser"),user.getLogin_name(),Key.LOG_SUCCESS);
            HelperClazz.renderJson(response, "{\"success\":true,\"msg\":\"用户删除成功！\"}");
        }else{
            logDao.saveLog(request,content,type,(User)request.getSession().getAttribute("LoginUser"),user.getLogin_name(),Key.LOG_ERROR);
            HelperClazz.renderJson(response, "{\"success\":true,\"msg\":\"用户删除失败！\"}");
        }
    }

    /**
     * 校验登录名是否存在
     * @param request
     * @param response
     */
    @RequestMapping(value = "/checkName")
    public void checkName(HttpServletRequest request, HttpServletResponse response) {
        String login_name = request.getParameter("login_name");
        String user_id = request.getParameter("user_id");

        boolean bl;
        if(HelperClazz.isEmpty(user_id)){
            bl =  rzBaseDao.chkIsExist("ss_user", "login_name", login_name)==0;
        }else{
            String login_name1_nameDb=userDao.getUserById(user_id).getLogin_name();
            if(login_name1_nameDb.equals(login_name)){
                bl=true;
            }else{
                bl = rzBaseDao.chkIsExist("ss_user", "login_name", login_name)==0;
            }
        }
        HelperClazz.renderJson(response, "{ \"valid\": " + bl + " }");
    }

    /**
     * 用户配置角色
     * @param request
     * @param response
     */
    @RequestMapping(value = "/configRoles")
    public void configRoles(HttpServletRequest request,HttpServletResponse response){
        String user_id=request.getParameter("user_id");
        String ids=request.getParameter("role_id");
        try {
            //清空角色
            this.userDao.delUserRoles(user_id);
            //配置新角色
            String[] idArray=ids.split(",");
            for(int i=0;i<idArray.length;i++){
                String role_id=idArray[i];
                this.userDao.configRoles(user_id,role_id);
            }
            HelperClazz.renderJson(response, "{\"success\":true,\"msg\":\"角色配置成功！\"}");

        }catch(Exception e) {
            e.printStackTrace();
            HelperClazz.renderJson(response, "{\"success\":false,\"msg\":\"角色配置失败！\"}");
        }
    }

    /**
     * 选择角色
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/selectRoles")
    public void selectRoles(HttpServletRequest request, HttpServletResponse response) {
        String user_id=request.getParameter("user_id");

        //查询所有角色
        List<Role> roles = new ArrayList<Role>();
        roles = roleDao.queryAllRoles();
        //查询已配置角色
        List<Map<String,Object>> list= this.userDao.queryRoleByUserId(user_id);

        HelperClazz.renderJson(response,"{\"roles\":"+JSON.toJSONString(roles)+",\"userRoles\":"+JSON.toJSONString(list)+"}");
    }

    @RequestMapping(value = "/toUpdatePwd")
    public String toUpdatePwd(Model modele,HttpServletRequest request){
        return "smartcity/pwdManage/pwdPage";
    }

    /**
     * 修改密码
     * @param request
     * @param response
     */
    @RequestMapping(value = "/updPwd")
    public void updPwd(HttpServletRequest request, HttpServletResponse response){
        int result=-1;
        User u=(User)request.getSession().getAttribute("LoginUser");
        String oldPwd=request.getParameter("user_pwd");
        String newPwd=request.getParameter("new_pwd");

        oldPwd=Md5.MD5(oldPwd);
        newPwd=Md5.MD5(newPwd);

        if(HelperClazz.isEmpty(u.getUser_id())) {
            HelperClazz.renderJson(response, "{\"success\":false,\"msg\":\"密码修改失败！\"}");
        }else{
            User reUser=userDao.getUserById(u.getUser_id());
            if(reUser.getPassword().equals(oldPwd)){
                User pUser=new User();
                pUser.setPassword(newPwd);
                pUser.setUser_id(u.getUser_id());
                result=userDao.updPwd(pUser);
                if(result!=-1){
                    HelperClazz.renderJson(response, "{\"success\":true,\"msg\":\"密码修改成功！\"}");
                }else{
                    HelperClazz.renderJson(response, "{\"success\":false,\"msg\":\"密码修改失败！\"}");
                }
            }else{
                HelperClazz.renderJson(response, "{\"success\":false,\"msg\":\"原始密码不正确，修改失败！\"}");
            }
        }
    }

    @RequestMapping(value = "/userDetail")
    public String userDetail(HttpServletRequest request, HttpServletResponse response) {
        String user_id=request.getParameter("user_id");
        User user= this.userDao.getUserById(user_id);
        request.setAttribute("user",user);
        //查询已配置角色
        List<Map<String,Object>> list= this.userDao.queryRoleByUserId(user_id);
        request.setAttribute("userRoles",list);

        return "smartcity/userManage/userDetail";
    }

    @RequestMapping(value = "/updateOrg")
    public void updateOrg(HttpServletRequest request, HttpServletResponse response){
        User user=new User();
        user.setUser_id(request.getParameter("user_id"));
        user.setOrg_id(request.getParameter("org_id"));
        user.setOrg_name(request.getParameter("org_name"));
        if(userDao.updateOrg(user)!=-1){
            HelperClazz.renderJson(response, "{\"success\":true,\"msg\":\"组织机构修改成功！\"}");
        }else{
            HelperClazz.renderJson(response, "{\"success\":false,\"msg\":\"组织机构修改失败！\"}");
        }
    }
    @RequestMapping(value = "/updatePm")
    public void updatePm(HttpServletRequest request, HttpServletResponse response){
        User user=new User();
        user.setUser_id(request.getParameter("user_id"));
        user.setPermission(request.getParameter("permission"));
        if(userDao.updatePm(user)!=-1){
            HelperClazz.renderJson(response, "{\"success\":true,\"msg\":\"可视范围修改成功！\"}");
        }else{
            HelperClazz.renderJson(response, "{\"success\":false,\"msg\":\"可视范围修改失败！\"}");
        }
    }

    /**
     * 重置用户密码
     * @param request
     * @param response
     */
    @RequestMapping(value = "/resetUserPwd")
    public void resetUserPwd(HttpServletRequest request,HttpServletResponse response){
        int result=-1;
        String id=request.getParameter("user_id");
        User user=userDao.getUserById(id);
        user.setPassword(Md5.MD5(ADMIN_INIT_PWD));
        result=this.userDao.updPwd(user);
        String type=Key.LOG_UPDATE;
        String content="重置用户密码："+user.getUser_name();
        if(result==0){
            logDao.saveLog(request,content,type,(User)request.getSession().getAttribute("LoginUser"),user.getLogin_name(),Key.LOG_SUCCESS);
            HelperClazz.renderJson(response, "{\"success\":true,\"msg\":\"重置用户密码成功！\"}");
        }else{
            logDao.saveLog(request,content,type,(User)request.getSession().getAttribute("LoginUser"),user.getLogin_name(),Key.LOG_ERROR);
            HelperClazz.renderJson(response, "{\"success\":true,\"msg\":\"重置用户密码失败！\"}");
        }
    }

}
